﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Openfree.Framework.DataAccess;
using System.Text;

public partial class Controls_Activity_GoodStocktaking : BaseUserControl
{
    private string TableName = "IC_Stocktaking";
    private string Key = "StocktakingID";
    private SqlCodeConfig codeConfig;
    private bool isreadonly;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            InitLoadData();
            tbGoodCode.Attributes.Add("onkeypress", "Openfree.prototype.EnterSubmit('" + tbGoodCode.ClientID + "',event);");
        }
        else
        {
            if (!string.IsNullOrEmpty(tbGoodCode.Text))
            {
                AddSelectByCode(tbGoodCode.Text);
                tbGoodCode.Text = "";
                tbGoodCode.Focus();
            }
        }
        GoodItemSelect.OnGoodItemSelectOk += new GoodItemSelectEventHandler(btnSelectOk_Click);
    }
    public void btnSearchGoodCode_Click(object sender, EventArgs e)
    {
        pnlSearchGoodCode.Visible = true;
    }
    private void InitLoadData()
    {
        P_LoginName.Text = SessionManager.Username;
        P_Department.Text = SessionManager.OrgName;
        ReadOnlyData(false);
    }

    public void ReadOnlyData(bool IsReadOnly)
    {
        isreadonly = IsReadOnly;
        P_StocktakingDate.ReadOnly = IsReadOnly; 
        P_Description.ReadOnly = IsReadOnly;
        P_LoginName.ReadOnly = true;
        P_Department.ReadOnly = true;
        pnlSearchGoodCode.Visible = false;
    }
    protected void btnSelect_Click(object sender, EventArgs e)
    {
        GoodItemSelect.OnSelect(sender, e);
    }
    private void ResetComponent()
    {
        hfStocktakingID.Value = string.Empty;
        P_LoginName.Text = SessionManager.Username;
        P_Department.Text = SessionManager.OrgName;
        pnlSearchGoodCode.Visible = false;
    }
    protected void btnSelectOk_Click(object sender, GoodItemSelectEventArgs e)
    {

        foreach (DataRow dr in e.SelectedRow)
        {
            DataRow[] drs = SessionManager.DataSet.Tables["IC_StocktakingItem"].Select("GoodsID='" + dr["GoodsID"].ToString() + "'");
            if (drs.Length > 0) continue;
            DataRow row2 = SessionManager.DataSet.Tables["IC_StocktakingItem"].NewRow();

            row2["StocktakingItemID"] = System.Guid.NewGuid().ToString();
            row2["GoodsID"] = dr["GoodsID"];
            row2["GoodsCode"] = dr["GoodsCode"];
            row2["Subject"] = dr["Subject"];
            row2["CategoryName"] = dr["CategoryName"];
            row2["CategoryID"] = dr["CategoryID"];
            row2["GoodsMaker"] = dr["GoodsMaker"];
            row2["TypeModel"] = dr["TypeModel"];
            row2["GoodsUnit"] = dr["GoodsUnit"];
            row2["ActiveCount"] = dr["ActiveCount"];
            row2["OldCount"] = dr["OldCount"];
            row2["BadCount"] = dr["BadCount"];

            row2["ActiveRealCount"] = dr["ActiveCount"];
            row2["OldRealCount"] = dr["OldCount"];
            row2["BadRealCount"] = dr["BadCount"]; 

            row2["IsCheck"] = "未确认";
            SessionManager.DataSet.Tables["IC_StocktakingItem"].Rows.Add(row2);
        }
        BindGridViewItems();
    }
    protected void AddSelectByCode(string code)
    {
        string cmdGoodsText = string.Format("SELECT T.*,A.SUBJECT AS CategoryName FROM {0} T LEFT JOIN " + GoodsCategoryAccess.TABLE_NAME + " A ON A.NODEID=T.CategoryID where 1=1 and T.GoodsCode='" + code + "'", "IC_Goods");
        DataSet ds = PMSAccess.GetDataSet(this.Connection, cmdGoodsText);
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            DataRow[] drs = SessionManager.DataSet.Tables["IC_StocktakingItem"].Select("GoodsID='" + dr["GoodsID"].ToString() + "'");
            if (drs.Length > 0) continue;
            DataRow row2 = SessionManager.DataSet.Tables["IC_StocktakingItem"].NewRow();

            row2["StocktakingItemID"] = System.Guid.NewGuid().ToString();
            row2["GoodsID"] = dr["GoodsID"];
            row2["GoodsCode"] = dr["GoodsCode"];
            row2["Subject"] = dr["Subject"];
            row2["CategoryName"] = dr["CategoryName"];
            row2["CategoryID"] = dr["CategoryID"];
            row2["GoodsMaker"] = dr["GoodsMaker"];
            row2["TypeModel"] = dr["TypeModel"];
            row2["GoodsUnit"] = dr["GoodsUnit"];
            row2["ActiveCount"] = dr["ActiveCount"];
            row2["OldCount"] = dr["OldCount"];
            row2["BadCount"] = dr["BadCount"];

            row2["ActiveRealCount"] = dr["ActiveCount"];
            row2["OldRealCount"] = dr["OldCount"];
            row2["BadRealCount"] = dr["BadCount"];

            row2["IsCheck"] = "未确认";
            SessionManager.DataSet.Tables["IC_StocktakingItem"].Rows.Add(row2);
        }
        BindGridViewItems();
    }

    public void ViewStocktaking(string stocktakingId)
    {
        this.isreadonly = true;
        ReadOnlyData(true);
        DataSet ds = PMSAccess.GetDataSet(this.Connection, "select T.*" + PMSAccess.AppendSql_UserOrg + " from IC_Stocktaking T where T.StocktakingID='" + stocktakingId + "'", TableName);
        SessionManager.DataSet = ds;
        PMSAccess.FillDataSet(this.Connection, SessionManager.DataSet, "select T.*,'已确认' as IsCheck,A.SUBJECT AS CategoryName from IC_StocktakingItem T LEFT JOIN " + GoodsCategoryAccess.TABLE_NAME + " A ON A.NODEID=T.CategoryID where StocktakingID='" + stocktakingId + "' ", "IC_StocktakingItem");
        if (ds.Tables[TableName].Rows.Count > 0)
        {
            DataRow row = ds.Tables["IC_Stocktaking"].Rows[0];
            P_StocktakingDate.Text = row["StocktakingDate"].ToString(); 
            P_Description.Text = row["Description"].ToString();
            P_LoginName.Text = row["UserName"].ToString();
            P_Department.Text = row["OrgName"].ToString();
        }
        BindGridViewItems();
        btnSearchGoodCode.Visible = false;
        btnSelect.Visible = false;
        btnSubmit.Visible = false;
        btnCancel.Text = "返回";
    }
    public void AddStocktaking()
    {
        this.isreadonly = false;
        ReadOnlyData(false);
        btnSelect.Visible = true;
        btnSubmit.Visible = true;
        btnSearchGoodCode.Visible = true;
        btnCancel.Text = "取消";
        P_StocktakingDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
        DataSet ds = PMSAccess.GetDataSet(this.Connection, "select * from " + this.TableName + " where 1=2 ", this.TableName);
        SessionManager.DataSet = ds;
        PMSAccess.FillDataSet(this.Connection, SessionManager.DataSet, "select  T.*,'未确认' as IsCheck,A.SUBJECT AS CategoryName from IC_StocktakingItem T LEFT JOIN " + GoodsCategoryAccess.TABLE_NAME + " A ON A.NODEID=T.CategoryID where 1=2 ", "IC_StocktakingItem");

    }
    public void btnSubmit_Click(object sender, EventArgs e)
    {
        PMSAccess.FillDataSet(this.Connection, SessionManager.DataSet, "select * from " + this.TableName + " where 1=2 ", this.TableName);

        DataRow row = SessionManager.DataSet.Tables[this.TableName].NewRow();
        string stockInId = System.Guid.NewGuid().ToString();
        row["StocktakingID"] = stockInId;
        row["StocktakingCode"] = PMSAccess.GetCode(EnumCodeKind.PanDian); 
        row["StocktakingDate"] = P_StocktakingDate.Text; 
        row["Description"] = P_Description.Text;
        row["LoginName"] = SessionManager.UserID;
        row["Department"] = SessionManager.OrgID;
        PMSAccess.AppendValue(ref row, EnumOperator.ADD);
        SessionManager.DataSet.Tables[this.TableName].Rows.Add(row);
        //更新库存
        //获取当前库存信息
        if (SessionManager.DataSet.Tables.Contains("IC_Goods"))
            SessionManager.DataSet.Tables.Remove("IC_Goods");
        PMSAccess.FillDataSet(this.Connection, SessionManager.DataSet, "select * from IC_Goods ", "IC_Goods");
        DataTable _gooddt = SessionManager.DataSet.Tables["IC_Goods"];
        DataRow[] _gooddrs = null;
        foreach (DataRow _dr in SessionManager.DataSet.Tables["IC_StocktakingItem"].Rows)
        {
            _dr["StocktakingID"] = stockInId;
            //修改库存量:可用库存量和实际库存量
            _gooddrs = _gooddt.Select("GoodsID='" + _dr["GoodsID"].ToString() + "'");
            if (_gooddrs.Length > 0)
            {
                _gooddrs[0]["ActiveCount"] = _dr["ActiveRealCount"];
                _gooddrs[0]["OldCount"] = _dr["OldRealCount"];
                _gooddrs[0]["BadCount"] = _dr["BadRealCount"]; 

            }
        }

        //一起更新
        PMSAccess.UpdateDataSet(this.Connection, new string[] { "IC_Goods", "IC_Stocktaking", "IC_StocktakingItem" }, SessionManager.DataSet);
        this.btnCancel_Click(sender, e);
        Alert("完成入库");
    }
    #region 具体项操作
    protected void BindGridViewItems()
    {
        DataTable dt = SessionManager.DataSet.Tables["IC_StocktakingItem"];
        gridViewItems.ShowFooter = false;
        gridViewItems.DataSource = dt;
        gridViewItems.DataBind();
        gridViewItems.Columns[13].Visible = !isreadonly;
        gridViewItems.Columns[14].Visible = !isreadonly;

    }
    protected void gridViewItems_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            ((HyperLink)e.Row.Cells[0].Controls[0]).NavigateUrl = "~/PMSWeb/GoodDetail.aspx?GoodsID=" + ((HiddenField)e.Row.Cells[9].Controls[1]).Value;
            (e.Row.Cells[9].Controls[3] as TextBox).ReadOnly = isreadonly;
            (e.Row.Cells[10].Controls[1] as TextBox).ReadOnly = isreadonly;
            (e.Row.Cells[11].Controls[1] as TextBox).ReadOnly = isreadonly;
            (e.Row.Cells[12].Controls[1] as TextBox).ReadOnly = isreadonly;
            e.Row.Cells[15].Attributes.Add("onclick", "return confirm('确认要删除吗？');");
            if (e.Row.Cells[13].Text == "已确认")
            {
                e.Row.Cells[14].Text = "";
                e.Row.Cells[15].Text = "";
            }
        }
    }
    protected void gridViewItems_RowEditing(object sender, GridViewEditEventArgs e)
    {
        string ID = (gridViewItems.Rows[e.NewEditIndex].Cells[9].Controls[1] as HiddenField).Value;
        string txt = (gridViewItems.Rows[e.NewEditIndex].Cells[9].Controls[3] as TextBox).Text.Trim();
        string oldtxt = (gridViewItems.Rows[e.NewEditIndex].Cells[10].Controls[1] as TextBox).Text.Trim();
        string badtxt = (gridViewItems.Rows[e.NewEditIndex].Cells[11].Controls[1] as TextBox).Text.Trim(); 
        DataRow[] rows = SessionManager.DataSet.Tables["IC_StocktakingItem"].Select("GoodsID='" + ID + "'");
        int countIn = 0;
        if (rows.Length > 0)
        {
            try
            {
                countIn = Convert.ToInt32(txt);
                rows[0]["ActiveRealCount"] = countIn;
            }
            catch
            {
                rows[0]["IsCheck"] = "未确认";
                Alert("实际可用数量请输入整数");
                return;
            }
            try
            {
                countIn = Convert.ToInt32(oldtxt);
                rows[0]["OldRealCount"] = countIn;
            }
            catch
            {
                rows[0]["IsCheck"] = "未确认";
                Alert("旧料回收数量请输入整数");
                return;
            }
            try
            {
                countIn = Convert.ToInt32(badtxt);
                rows[0]["BadRealCount"] = countIn;
            }
            catch
            {
                rows[0]["IsCheck"] = "未确认";
                Alert("报废数量请输入整数");
                return;
            } 
            rows[0]["IsCheck"] = "已确认";
            rows[0]["Description"] = (gridViewItems.Rows[e.NewEditIndex].Cells[12].Controls[1] as TextBox).Text.Trim(); ;
        }
        BindGridViewItems();
    }

    protected void gridViewItems_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string ID = (gridViewItems.Rows[e.RowIndex].Cells[9].Controls[1] as HiddenField).Value;
        DataRow[] rows = SessionManager.DataSet.Tables["IC_StocktakingItem"].Select("GoodsID='" + ID + "'");
        if (rows.Length > 0)
        {
            foreach (DataRow row in rows)
            {
                if (row.RowState != DataRowState.Deleted)
                {
                    row.Delete();
                }
            }

        }
        BindGridViewItems();
    }
    public void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("StocktakingManager.aspx");
    }
    #endregion
}
